<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传单张图片原生</title>
</head>

<body>
<h2>方法2</h2>
<h2>http://localhost:8080/upTextandImg3.html</h2>
<input type="file" class="file" name="file" multiple="multiple"/><br/><br/>

<a>产品类型：</a>
<select id="categoryID" name="cid">
    <option value="1">11</option>
    <option value="2">22</option>
    <option value="3">33</option>
</select>
<br/>
<br/>

<a>价钱：</a><input type="text" name="price" id="price"><br/><br/>
<a>库存：</a><input type="text" name="stock" id="stock"><br/><br/>
<a>状态：</a>
<select name="status" id="status">
    <option value="1">在售</option>
    <option value="2">22</option>
    <option value="3">33</option>
</select>
<br/><br/>

<p>商品详细描述</p>
<input type="text" name="details" id="detail">

<br/><br/>

<br>
<button id="btn">upload</button>
</body>
<script>
    // 上传文件 创建FormData
    let formData = new FormData()

    //将选择的文件放入formData
    document.querySelector('.file').addEventListener('change', function (e) {
        let files = e.target.files
        if (!files.length) return
        // 遍历FileList对象，拿到多个图片对象
        for (let i = 0; i < files.length; i++) {
            // formData中的append方法 如果已有相同的键，则会追加成为一个数组  注意:这里需要使用formData.getAll()获取
            formData.append('file', files[i], files[i].name)
        }
        console.log(formData.getAll('file'))

    })

    //点击按钮发起请求
    let btn = document.querySelector('#btn')
    btn.onclick = function () {
        //获取文本框的值，并添加进formData
        let categoryID = document.querySelector('#categoryID')
        formData.append("categoryID", categoryID.value)
        let price = document.querySelector('#price')
        formData.append("price", price.value)
        let stock = document.querySelector('#stock')
        formData.append("stock", stock.value)
        let status = document.querySelector('#status')
        formData.append("status", status.value)
        let detail = document.querySelector('#detail')
        formData.append("detail", detail.value)


        // 将formdata发送到后台即可
        // 发起请求
        let xhr = new XMLHttpRequest()
        xhr.open('post', '/movements', true)
        xhr.send(formData)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                alert('success')
            }
        }
    }

</script>

</html>
